﻿using CommonBase;
using CommonClass;
using FileLib;
using Microsoft.Practices.Prism.Commands;
using SurveillanceLib;
using SurveillancePro.Base.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using VideoMgtModule.DataEnum;

namespace VideoMgtModule.ViewModels
{
    /// <summary>
    /// 流数据录像
    /// </summary>
    public class ViewModel_RecordVideo : WorkspaceViewModel
    {
        #region Const Fields

        private readonly string SAVEPATH_RECORDVIDEO;

        #endregion

        #region Private Fields

        private bool _isRecording; // 表示是否正在录像中
        private string _saveRecordVideoFileName; // 录像文件名称
        private Window _infoWindow;
        private TagModel _panelTag;
        private DelegateCommand _cmdStartDataRecord, _cmdStopDataRecord, _cmdCloseWindow;

        #endregion

        #region Constructor

        /// <summary>
        /// 
        /// </summary>
        /// <param name="infoWindow"></param>
        /// <param name="panelTag">视频窗口 Tag 值</param>
        public ViewModel_RecordVideo(Window infoWindow,
            TagModel panelTag)
        {
            if (panelTag == null)
            {
                MessageBox.Show("视频窗口参数不正确！", ConstantString.MSG_COMPANY);
                return;
            }

            infoWindow.Closing += (s, e) =>
            {
                if (this._isRecording) // 正在录像中
                {
                    try
                    {
                        if (this._panelTag.Driver_Instance != null &&
                            this._panelTag.Driver_Instance.StopDataRecord(
                            int.Parse(this._panelTag.Panel_SelectedChannel))) // 停止流数据录像
                        {
#if DEBUG
                            Debug.WriteLine("结束保存当前录像视频流");
#endif
                        }
                        else
                        {
#if DEBUG
                            Debug.WriteLine("录像文件保存失败！");
#endif
                        }
                    }
                    catch (System.Exception ex)
                    {
#if DEBUG
                        Debug.WriteLine(ex.Message);
#endif
                    }
                }
            };

            if (string.IsNullOrWhiteSpace(SurveillanceUtilities.RecordVideoPath))
                SAVEPATH_RECORDVIDEO = SurveillanceUtilities.USERCONFIG_RECORDVIDEOPATH_DEFAULT;
            else
                SAVEPATH_RECORDVIDEO = SurveillanceUtilities.RecordVideoPath;

            this._infoWindow = infoWindow;
            this._panelTag = panelTag;
            this._isRecording = false; // 未录像
            this._recordVideoPath = this.SAVEPATH_RECORDVIDEO;

            FileOperation.CreatDirectory(SAVEPATH_RECORDVIDEO); // 创建文件夹
            _fillDataTypesList(); // 加载 DataTypes 下拉框
        }

        #endregion

        #region Base Class Overrides

        protected override void OnDispose()
        {
            _dispose();
        }

        #endregion

        #region Public Property

        /// <summary>
        /// DataTypes
        /// </summary>
        public List<ArgModel> DataTypes { get; private set; }

        /// <summary>
        /// 录像保存格式
        /// </summary>
        public int DataType { get; set; }

        private string _recordVideoPath;
        /// <summary>
        /// 文件保存路径
        /// </summary>
        public string RecordVideoPath
        {
            get
            {
                return _recordVideoPath;
            }
            set
            {
                if (_recordVideoPath == value) return;
                _recordVideoPath = value;
                base.OnPropertyChanged("RecordVideoPath");
            }
        }

        /// <summary>
        /// 开始保存
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_StartDataRecord
        {
            get
            {
                if (_cmdStartDataRecord == null)
                {
                    _cmdStartDataRecord = new DelegateCommand(_startDataRecord, _canStartDataRecord);
                }
                return _cmdStartDataRecord;
            }
        }

        /// <summary>
        /// 结束保存
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_StopDataRecord
        {
            get
            {
                if (_cmdStopDataRecord == null)
                {
                    _cmdStopDataRecord = new DelegateCommand(_stopDataRecord, _canStopDataRecord);
                }
                return _cmdStopDataRecord;
            }
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_CloseWindow
        {
            get
            {
                if (_cmdCloseWindow == null)
                {
                    _cmdCloseWindow = new DelegateCommand(_closeWindow, _canCloseWindow);
                }
                return _cmdCloseWindow;
            }
        }

        #endregion

        #region Private Methods

        #region DelegateCommand

        private bool _canStartDataRecord()
        {
            return !this._isRecording;
        }

        private bool _canStopDataRecord()
        {
            return this._isRecording;
        }

        private bool _canCloseWindow()
        {
            return true;
        }


        /// <summary>
        /// 开始保存
        /// </summary>
        private void _startDataRecord()
        {
            try
            {
                _saveRecordVideoFileName = Path.Combine(SAVEPATH_RECORDVIDEO, 
                    string.Format("RecordVideo_{0}", DateTime.Now.ToString("yyyyMMddHHmmss"))); // 保存的文件名称

                if (this._panelTag.Driver_Instance != null &&
                    this._panelTag.Driver_Instance.StartDataRecord(int.Parse(this._panelTag.Panel_SelectedChannel),
                    _saveRecordVideoFileName, DataType)) // 开始流数据录像
                {
#if DEBUG
                    Debug.WriteLine("开始保存当前录像视频流");
#endif
                    this._isRecording = true; // 录像中
                    RecordVideoPath = _saveRecordVideoFileName;
                }
                else
                {
#if DEBUG
                    Debug.WriteLine("录像失败！");
#endif
                    MessageBox.Show("录像失败！", ConstantString.MSG_COMPANY);
                }

                SurveillancePro.Base.Reflector.WorkingStateProperty.OnWorkingStatePropertyChanged(this); // 更新界面
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        /// <summary>
        /// 结束保存
        /// </summary>
        private void _stopDataRecord()
        {
            try
            {
                if (this._panelTag.Driver_Instance != null &&
                    this._panelTag.Driver_Instance.StopDataRecord(
                    int.Parse(this._panelTag.Panel_SelectedChannel))) // 停止流数据录像
                {
#if DEBUG
                    Debug.WriteLine("结束保存当前录像视频流");
#endif
                    MessageBox.Show("录像结束，文件保存成功！", ConstantString.MSG_COMPANY);
                }
                else
                {
#if DEBUG
                    Debug.WriteLine("录像文件保存失败！");
#endif
                    MessageBox.Show("录像文件保存失败！", ConstantString.MSG_COMPANY);
                }

                SurveillancePro.Base.Reflector.WorkingStateProperty.OnWorkingStatePropertyChanged(this); // 更新界面
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            this._isRecording = false; // 未录像
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        private void _closeWindow()
        {
            this._infoWindow.DialogResult = false;
        }

        #endregion

        /// <summary>
        /// 填充视频格式下拉值
        /// </summary>
        private void _fillDataTypesList()
        {
            ArgModel argType;
            DataTypes = new List<ArgModel>();

            // 填充 VideoDataTypeEnum 枚举
            foreach (VideoDataTypeEnum dataType in Utilities.GetEnumValues<VideoDataTypeEnum>())
            {
                argType = new ArgModel()
                {
                    iKey = (int)dataType,
                    sValue = Utilities.GetEnumDisplayDescription(dataType),
                };
                DataTypes.Add(argType);
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        private void _dispose()
        {
            try
            {
                if (DataTypes != null)
                    DataTypes.Clear();
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion
    }
}
